package com.moyu.oauth.controller;

import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moyu.common.core.enums.ResultCode;
import com.moyu.common.redis.service.RedisService;
import com.moyu.oauth.client.UserClient;
import com.moyu.oauth.dto.User;
import com.moyu.oauth.dto.UserLoginDTO;
import com.moyu.oauth.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 赵彦博
 * @Date 2024/11/29 19:23
 */
@RestController
@RequestMapping("/auths")
public class AuthController {

    private final UserClient userClient;

    @Autowired
    private RedisService redisService;

    public AuthController(UserClient userClient) {
        this.userClient = userClient;
    }

    @PostMapping("/doLogin")
    public SaResult doLogin(@RequestBody UserLoginDTO userLoginDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        User user = userClient.queryUser(userLoginDTO.getUsername()).getData();
        if (user == null) {
            return SaResult.error(ResultCode.FAILED_USER_NOT_EXISTS.getMsg());
        }
        if (BCryptUtils.matchesPassword(userLoginDTO.getPassword(), user.getPassword())) {
            // 判断
            StpUtil.setStpLogic(new StpLogicJwtForSimple());
            StpUtil.login(user.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            System.out.println(tokenInfo);
            return SaResult.ok("登录成功").setData(tokenInfo);
        }
        return SaResult.error(ResultCode.FAILED_LOGIN.getMsg());
    }

    // 查询登录状态
    @RequestMapping("/isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    // 测试注销
    @RequestMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

}
